package org.example.fastproject.core.security;

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import org.example.fastproject.core.bean.ViewResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author 王海舟
 * @Date 2023/1/18 12:33
 * @PackageName:org.example.fastproject.core.security
 * @ClassName: MyAuthenticationEndpoint
 * @Description: 认证失败处理类
 * @Version 1.0
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException, ServletException {
        int status = response.getStatus();
        if(status == HttpStatus.HTTP_NOT_FOUND)
            return;
        //设置响应格式
        response.setStatus(HttpStatus.HTTP_OK);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        //生成json数据
        ViewResult viewResult = ViewResult.error(HttpStatus.HTTP_UNAUTHORIZED,"未认证");
        String json = JSONUtil.toJsonStr(viewResult);
        //返回数据
        PrintWriter writer = response.getWriter();
        writer.print(json);
        writer.close();
    }
}
